import {
  fetchHome
} from '../../services/home/home';
import {
  fetchGoodsList
} from '../../services/good/fetchGoods';
import Toast from 'tdesign-miniprogram/toast/index';
const config = require('../../serverUtils/config.js');
const http = require('../../serverUtils/httputils.js');
Page({
  data: {
    dateRange: '',
    timePickVis: false,
    warnList: [],
    minDate: 0,
    selectDay: [],
    imgSrcs: [],
    deviceList: [],
    goodsList: [],
    goodsListLoadStatus: 0,
    pageLoading: false,
    current: 1,
    autoplay: true,
    duration: '500',
    interval: 5000,
    navigation: {
      type: 'dots'
    },
    weatherList: [],
    swiperImageProps: {
      mode: 'scaleToFill'
    },
    selectData: {
      value: 0,
      label: '总体统计'
    },
    timeParams: {
      startDate: '',
      endDate: ""
    },
    monitorPointInfoId: '',
    monitorsName: '',
    cityVisible: false,
    monitors: [{
        label: '北京市',
        value: '北京市'
      },
      {
        label: '上海市',
        value: '上海市'
      },
      {
        label: '广州市',
        value: '广州市'
      },
      {
        label: '深圳市',
        value: '深圳市'
      },
      {
        label: '成都市',
        value: '成都市'
      },
    ],
  },

  privateData: {
    tabIndex: 0
  },

  goodListPagination: {
    index: 0,
    num: 20,
  },


  onPickerChange(e) {
    const id = e.detail?.value?.[0]
    this.setData({
      monitorPointInfoId: id
    })
    this.searchTotalstatistics({
      quickDate: 3,
      startDate: this.data.timeParams.startDate,
      endDate: this.data.timeParams.endDate,
      monitorPointInfoId: this.data.monitorPointInfoId
    })
  },
  onShow() {},
  showTimePicker() {
    this.setData({
      timePickVis: true
    })
  },
  onLoad() {
    const oneMonthAgoTimestamp = new Date();
    oneMonthAgoTimestamp.setMonth(oneMonthAgoTimestamp.getMonth() - 1);
    // console.log('Date.now(), oneMonthAgoTimestamp.getTime()', Date.now(), oneMonthAgoTimestamp.getTime());
    const now = new Date()
    // const nowDateString = `${now.getFullYear()}-${now.getMonth()+1}-${now.getDate()}`
    // const moutDateString = `${oneMonthAgoTimestamp.getFullYear()}-${oneMonthAgoTimestamp.getMonth()+1}-${oneMonthAgoTimestamp.getDate()}`

    this.setData({
      dateRange: this.timeFormat(new Date(), oneMonthAgoTimestamp),
      minDate: 1514764800000,
      selectDay: [Date.now(), oneMonthAgoTimestamp.getTime()]
    })
    setTimeout(() => {

      // this.setData({
      //   timePickVis: true
      // })

    }, 200);
    this.init();
    this.getWarnInfo()
    http.getRequest(
      null,
      config.monitorpointinfoList, {},
      (res) => {
        this.setData({
          monitorsName: res.data?.[0].monitorpointname,
          monitorPointInfoId: res.data?.[0].id,
          monitors: [...res.data, ...res.data].map(item => {
            return {
              ...item,
              label: item.monitorpointname,
              value: item.id
            }
          })
        })
        this.searchTotalstatistics({
          quickDate: 3,
          startDate: this.data.timeParams.startDate,
          endDate: this.data.timeParams.endDate,
          monitorPointInfoId: this.data.monitorPointInfoId
        })
      }
    )

    http.getRequest(
      null,
      config.deviceInfo, {
        current: 1,
        size: 1000
      },
      (res) => {
        this.setData({
          deviceList: res.data.records.map(item => {
            return {
              ...item,
              nyEquipmentinfoNewDataList: item.nyEquipmentinfoNewDataList?.map(it => ({
                ...it,
                imgName: this.getImgName(it.key)
              }))
            }
          })
        })

      }
    )


  },
  handleTimeConfirm(e) {
    console.log('time', e);
    const {
      value
    } = e.detail
    let start = new Date(value[0])
    let end = new Date(value[1])
    // console.log('start', start, end);

    // // 获取年、月、日、小时、分钟和秒
    // var smonth = start.getMonth() + 1;
    // var sday = start.getDate();
    // var emonth = end.getMonth() + 1;
    // var eday = end.getDate();


    this.setData({
      dateRange: this.timeFormat(end, start),
      timeParams: {
        startDate: this.timestampToparma(value[0]),
        endDate: this.timestampToparma(value[1]),
      }
    })
    this.searchTotalstatistics({
      quickDate: '',
      startDate: this.timestampToparma(value[0]),
      endDate: this.timestampToparma(value[1]),
      monitorPointInfoId: this.data.monitorPointInfoId
    })
  },
  padZero(number) {
    return number < 10 ? '0' + number : number;
  },
  timestampToparma(timestamp) {
    var date = new Date(timestamp); // 将时间戳转换为毫秒
    var year = date.getFullYear();
    var month = this.padZero(date.getMonth() + 1);
    var day = this.padZero(date.getDate());
    var hours = this.padZero(date.getHours());
    var minutes = this.padZero(date.getMinutes());
    var seconds = this.padZero(date.getSeconds());
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
  },
  timeFormat(s, e) {
    const nowDateString = `${s.getMonth()+1}月${s.getDate()}日`
    const moutDateString = `${e.getMonth()+1}月${e.getDate()}日`

    return `${moutDateString}-${nowDateString}`
  },
  onTitlePicker() {
    this.setData({
      cityVisible: true,
    });
  },
  searchTotalstatistics({
    quickDate,
    startDate,
    endDate,
    monitorPointInfoId
  }) {
    http.postRequest(
      null,
      config.allTaiShi, {
        startDate,
        endDate,
        quickDate,
        monitorPointInfoId
      },
      (res) => {
        this.getNewData(res.data.spDataList)
      }
    )
  },
  getImgName(name) {
    if (name == null) return
    if (name.includes("空气") || name.includes("温度")) {
      return 'kqsd'
    } else if (name.includes("大气") || name.includes("气压")) {
      return 'dqyl'
    } else if (name.includes("光照")) {
      return 'gzd'
    } else if (name.includes("风速")) {
      return 'fs'
    } else if (name.includes("风向")) {
      return 'fx'
    } else if (name.includes("土壤")) {
      return 'trsd'
    } else if (name.includes("降雨")) {
      return 'jyl'
    } else if (name.includes("二氧")) {
      return 'eyht'
    } else if (name.includes("电导率")) {
      return 'dd'
    } else if (name.includes("水质")) {
      return 'ph'
    } else if (name.includes("液位")) {
      return 'yw'
    } else if (name.includes("数目") || name.includes("数量")) {
      return 'sl'
    } else if (name.includes("雨量")) {
      return 'yl'
    } else {
      return 'eyht'
    }
  },
  getNewData(val) {
    if (val == null || val.length < 1) return
    for (let i = 0; i < val.length; i++) {
      let newData = val[i].newData
      if (newData != null) {
        let newDataList = val[i].detailList.nyEquipmentinfoNewDataList
        if (newDataList != null && newDataList.length > 0) {
          for (let j = 0; j < newDataList.length; j++) {
            if ((newDataList[j].value != "0" && newDataList[j].value != "0.0") || newDataList[j].key == '风向') {
              this.setData({
                weatherList: [...this.data.weatherList, {
                  id: i * j,
                  name: newDataList[j].key,
                  value: newDataList[j].value,
                  imgName: this.getImgName(newDataList[j].key)
                }]
              })

            }
          }
        }
      }
    }
  },
  getWarnInfo() {
    http.getRequest(
      null,
      config.warnInfo, {
        current: 1,
        size: 5
      },
      (res) => {
        // console.log(res.data.records, 'records');
        this.setData({
          warnList: res.data.records
        })
      },
      (err) => {

      },
    )
  },
  onReachBottom() {
    if (this.data.goodsListLoadStatus === 0) {
      this.loadGoodsList();
    }
  },

  onPullDownRefresh() {
    this.init();
  },

  init() {
    this.loadHomePage();
  },
  goDivceDetail(e) {
    const {
      id,
      equipmenttypename
    } = e.currentTarget.dataset
    console.log('e.currentTarget.dataset', e.currentTarget.dataset);
    wx.navigateTo({
      url: '/pages/deviceDetail/deviceDetail?id=' + id + '&equipmentTypeName=' + equipmenttypename,
    })
  },
  toWarnPage() {
    wx.switchTab({
      url: '/pages/warnList/warnList',
    })
  },
  statechange(e) {
    console.log('live-player code:', e.detail.code)
  },
  error(e) {
    console.error('live-player error:', e.detail.errMsg)
  },
  loadHomePage() {
    wx.stopPullDownRefresh();

    this.setData({
      pageLoading: true,
    });
    fetchHome().then(({
      swiper,
      tabList
    }) => {
      this.setData({
        tabList,
        imgSrcs: swiper,
        pageLoading: false,
      });
      this.loadGoodsList(true);
    });
  },

  tabChangeHandle(e) {
    console.log("🚀 ~ tabChangeHandle ~ e:", e)
    // value label
    this.setData({
      selectData: e.detail
    });
    this.loadGoodsList(true);
  },

  onReTry() {
    this.loadGoodsList();
  },

  async loadGoodsList(fresh = false) {
    if (fresh) {
      wx.pageScrollTo({
        scrollTop: 0,
      });
    }

    this.setData({
      goodsListLoadStatus: 1
    });

    const pageSize = this.goodListPagination.num;
    let pageIndex = this.privateData.tabIndex * pageSize + this.goodListPagination.index + 1;
    if (fresh) {
      pageIndex = 0;
    }

    try {
      const nextList = await fetchGoodsList(pageIndex, pageSize);
      this.setData({
        goodsList: fresh ? nextList : this.data.goodsList.concat(nextList),
        goodsListLoadStatus: 0,
      });

      this.goodListPagination.index = pageIndex;
      this.goodListPagination.num = pageSize;
    } catch (err) {
      this.setData({
        goodsListLoadStatus: 3
      });
    }
  },

  goodListClickHandle(e) {
    const {
      index
    } = e.detail;
    const {
      spuId
    } = this.data.goodsList[index];
    wx.navigateTo({
      url: `/pages/goods/details/index?spuId=${spuId}`,
    });
  },

  goodListAddCartHandle() {
    Toast({
      context: this,
      selector: '#t-toast',
      message: '点击加入购物车',
    });
  },

  navToSearchPage() {
    wx.navigateTo({
      url: '/pages/goods/search/index'
    });
  },

  navToActivityDetail({
    detail
  }) {
    const {
      index: promotionID = 0
    } = detail || {};
    wx.navigateTo({
      url: `/pages/promotion-detail/index?promotion_id=${promotionID}`,
    });
  },
});